﻿/**************************************************************
 *
 * 命名空间：Sgr.UPMS.Application.Commands.Menus
 * 创建时间：2025/3/20
 * 描述：创建菜单命令处理器
 *
 **************************************************************/

using MediatR;
using Sgr.Application.Commands;
using Sgr.UPMS.Domain.Menus;
using System.Threading;
using System.Threading.Tasks;

namespace Sgr.UPMS.Application.Commands.Menus
{
    /// <summary>
    /// 创建菜单命令处理器
    /// </summary>
    public class CreateMenuCommandHandler
         : IRequestHandler<CreateMenuCommand, CommandResult<bool>>
    {
        private readonly IMenuManage _menuManage;
        private readonly IMenuRepository _menuRepository;

        /// <summary>
        /// 构造函数
        /// </summary>
        public CreateMenuCommandHandler(
            IMenuManage menuManage,
            IMenuRepository menuRepository)
        {
            _menuManage = menuManage;
            _menuRepository = menuRepository;
        }

        /// <summary>
        /// 处理命令
        /// </summary>
        /// <param name="command"></param>
        /// <param name="cancellationToken"></param>
        /// <returns></returns>
        public async Task<CommandResult<bool>> Handle(
            CreateMenuCommand command,
            CancellationToken cancellationToken)
        {
            // 创建菜单
            // 规则1：同级菜单名称唯一性
            // 规则2：菜单层级不超过5级
            // 规则3：目录节点只能放置到目录节点下
            // 规则4：菜单节点只能放置到目录节点下
            var menu = await _menuManage.CreateAsync(
                command.Name,
                command.Type,
                command.ParentId,
                command.Permission,
                cancellationToken);

            //如果路由名称不为空，则验证路由名称唯一性
            if (!string.IsNullOrEmpty(command.RouteName))
            {
                var routeNameExists = await _menuManage.ValidateRouteNameUniquenessAsync(command.RouteName, null, cancellationToken);
                if (!routeNameExists.IsComply)
                    return CommandResult.Invalid<bool>(routeNameExists.Message);
            }

            // 设置基本信息
            menu.UpdateBasicInfo(
                command.Name,
                command.Icon,
                command.RouteName,
                command.RoutePath,
                command.ComponentPath,
                command.RedirectPath,
                command.Permission,
                command.Description,
                command.Order);

            // 设置配置信息
            menu.UpdateConfig(
                command.ExternalLink,
                command.Hidden,
                command.KeepAlive,
                command.Affix,
                command.Target);

            // 保存菜单
            await _menuRepository.InsertAsync(menu, cancellationToken);

            // 返回成功结果
            return CommandResult.Success(true, "菜单创建成功");
        }
    }
}